/**
 * Created by sam on 16-10-19.
 */
//var request = require('request');
var dao = require('./dao');

function loadMbRank(job,ep) {

        var data = {
            keyword: job.keyword,
            stock: 1,
            sort: job.category,
            self: job.is_jd_deliver,
            page: job.pageNum,
            _format_: 'json'
        };
        //console.log(data);
        var pData = require('querystring').stringify(data);
        request("http://so.m.jd.com/ware/searchList.action?" + pData
            , function (error, response, body) {
                if (response.statusCode == 200) {
                    var json = JSON.parse(body);
                    var val = JSON.parse(json.value);
                    var wareList = val.wareList;
                    //console.log(wareList.length)
                    //console.log("keyword:"+data.keyword+",length:"+wareList.length+",page:"+data.page);
                    for (var i in wareList) {

                        var obj = wareList[i];
                        obj.keyword = data.keyword;
                        obj.pageNum = data.page;
                        obj.index = (parseInt(i) + 1);
                        obj.psort = data.sort;
                        obj.wtype = data.self;

                        dao.saveMbRank(obj);
                    }
                    ep.emit('next_job', data);
                }
            });
}

module.exports.loadMbRank = loadMbRank;
module.exports.post = post;


function post(url,data,fn){
    data=data||{};
    var content=require('querystring').stringify(data);
    var parse_u=require('url').parse(url,true);
    var isHttp=parse_u.protocol=='http:';
    var options={
        host:parse_u.hostname,
        port:parse_u.port||(isHttp?80:443),
        path:parse_u.path,
        method:'POST',
        headers:{
            'Content-Type':'application/x-www-form-urlencoded',
            'Content-Length':content.length
        }
    };
    var req = require(isHttp?'http':'https').request(options,function(res){
        var _data='';
        res.on('data', function(chunk){
            _data += chunk;
        });
        res.on('end', function(){
            if(fn) fn(_data);
        });
    });
    req.write(content);
    req.end();
}
